//解析参数
const parseUrl = (url = "")=>{
    //只保留?key=value部分
    var query_str = ""
    //截取query
    var index = url.indexOf('?')
    if(index != -1){
        query_str = url.substring(index)
    }

    var params = new URLSearchParams(query_str)

    //转json对象
    //完整参数
    const full_result = {}
    //分页参数
    const page_params = {}
    //表单参数
    const form_params = {}
    for (let pair of params.entries()) {
        //字段填充
        full_result[pair[0]] = pair[1]
        //区分参数类别
        if(pair[0] == "pageNumber" || pair[0] == "pageSize"){
            page_params[pair[0]] = pair[1]
        }else{
            form_params[pair[0]] = pair[1]
        }
    }
    return {
        full_result, page_params, form_params
    }
}

//根据表单条件对总数据过滤
const formDataFilter = (_data = [], form_params = {})=>{
    //深拷贝
    var data = JSON.parse(JSON.stringify(_data))
    //每行数据进行过滤
    data.list = data.list.filter(row=>{
        return rowDataFiter(row,form_params)
    })
    //重新数据长度
    data.total = data.list.length

    return data
}

//每行过滤规则
const rowDataFiter = (row = {}, form_params = {})=>{
    //默认保留
    var filter_status = true
    //遍历查询字段,有一个不满足则进行过滤
    for(var key in form_params){
        //当前字段对应的值
        var value = row[key]
        //当前要字段要查询过滤的值
        var filter_value = form_params[key]
        //如果不匹配
        if(!value.includes(filter_value)){
            //此行数据不保留
            filter_status = false
            //终止本轮循环
            break;
        }
    }
    return filter_status
}

//分页数据过滤
const pageDataFilter = (_data = [], page_params = {} )=>{
    //深拷贝
    var data = JSON.parse(JSON.stringify(_data))
    //初始化分页参数
    var pageNumber = page_params.pageNumber || 1
    var pageSize = page_params.pageSize || 10
    //起始下标
    var start = (pageNumber - 1) * pageSize
    //结束下标
    var end = start + Number(pageSize)
    //返回切割后数据
    return data.slice(start,end)
}

//查询和过滤数据
export const getFilterData = (_data = [], url = "")=>{
    //深拷贝
    var data = JSON.parse(JSON.stringify(_data))
    //查询参数
    const {full_result, page_params, form_params} = parseUrl(url)
    //表单条件过滤
    data = formDataFilter(data,form_params)
    //分页数据过滤
    data.list = pageDataFilter(data.list, page_params)

    return data
}